﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using GianosNET.Common.Classes;
using SQLPXBase;

namespace GianosNET.Services.WindowsServiceRestarterSVC
{
    public class WindowsServiceRestarterSVC : LoopingService
    {
        private const string svcName = "WINDOW SERVICE RESTART SERVICE";
        private const string vNum = "1.0";

        public WindowsServiceRestarterSVC(ServerInfo info) : this(false, info)
        {
        }

        public WindowsServiceRestarterSVC(bool enableAutoStart, ServerInfo info)
            : this(new Hashtable(), null, enableAutoStart, info)
        {
        }

        public WindowsServiceRestarterSVC(Hashtable config, ProxyManager<sqlStatus> statusProxyMgr, bool enableAutoStart,
                                       ServerInfo info)
            : base(svcName, vNum, config, statusProxyMgr, enableAutoStart, info)
        {
        }

        private string WindowsServiceName;
        private string ProcessName;

        protected override void CustomGetConfiguration()
        {
            WindowsServiceName = config["ServiceName"] as string;
            if (WindowsServiceName == null)
                throw new Exception("Nome del servizio non corretto.");
            ProcessName = config["ProcessName"] as string;
        }

        protected override void CustomJobExecution(BackgroundWorker job)
        {
            ServiceController svCtrl = new ServiceController(WindowsServiceName);
            ServerInfo.EnqueueInLog(MainLogId, string.Format("[{0}] - {1}", DateTime.Now, WindowsServiceName));
            if (svCtrl.Status == ServiceControllerStatus.Running)
            {
                ServerInfo.EnqueueInLog(MainLogId, "Arresto del servizio.");
                svCtrl.Stop();
                try
                {
                    svCtrl.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 2, 0));
                }
                catch (System.ServiceProcess.TimeoutException ex)
                {
                    throw new Exception("Impossibile fermare il servizio: timeout.");
                }
                finally
                {
                    if (svCtrl.Status != ServiceControllerStatus.Stopped)
                    {
                        if (ProcessName != null)
                        {
                            ServerInfo.EnqueueInLog(MainLogId, "Tentativo di KILL.");
                            Process[] process = Process.GetProcessesByName(ProcessName);
                            foreach (Process p in process)
                                p.Kill();
                        }
                    }
                }
            }

            ServerInfo.EnqueueInLog(MainLogId, "Avvio del servizio");
            svCtrl.Start();
        }
    }
}